<template>
    <div id="monitor-rule-list">
        <el-row class="search-bar">
            <el-col :span="4">
                <el-input v-model="searchParams.codeOrName" placeholder="请输入监控规则编码或名称" size="mini"></el-input>
            </el-col>
            <el-col :span="16" style="padding: 0 10px">
                <el-button size="mini" type="primary" @click="handleBtn('search')">查询</el-button>
                <el-button size="mini" type="primary" @click="handleBtn('refresh')">刷新</el-button>
                <el-button size="mini" type="primary" @click="handleBtn('add')">新增</el-button>
                <el-button size="mini" type="danger" @click="handleBtn('deletes')">删除</el-button>
                <el-button size="mini" type="primary" @click="handleBtn('enable')">启用</el-button>
                <el-button size="mini" type="danger" @click="handleBtn('unable')">禁用</el-button>
                <el-button size="mini" type="primary" @click="handleBtn('run')">运行勾稽</el-button>
            </el-col>
        </el-row>

        <RiskTableP
            ref="risk-table"
            :tableConfig="tableConfig"
            :tableData="tableData"
            :column="columns"
            :paging="paging"
            :searchParams="searchParams"
            v-loading="tableLoading"
            @page-change="getTableData"
            @current-change="handleCurrentRow"
            :key="tableKey"
            style="height: calc(100% - 70px)"
        >
            <template #operation="{ row }">
                <RiskIconButton type="primary" icon="el-icon-view" topTitle="查看" @on-click="handleBtn('look', row)"></RiskIconButton>
                <RiskIconButton type="primary" icon="el-icon-edit" topTitle="编辑" @on-click="handleBtn('edit', row)"></RiskIconButton>
                <RiskIconButton type="primary" icon="el-icon-document-copy" topTitle="复制" @on-click="handleBtn('copy', row)"></RiskIconButton>
                <RiskIconButton type="danger" icon="el-icon-delete" topTitle="删除" @on-click="handleBtn('delete', row)"></RiskIconButton>
            </template>
        </RiskTableP>

        <!-- 删除弹窗 -->
        <yh-dialog title="确定删除以下监控规则吗？" :visible.sync="deleteVisible" width="600px" drag>
            <div>
                {{ checkRowKeys.map(item => item).join(',') }}
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="deleteVisible = false" size="mini">取 消</el-button>
                <el-button @click="handleDelete" :loading="delLoading" size="mini" type="primary">确 定 </el-button>
            </div>
        </yh-dialog>

        <!-- 启用/禁用 -->
        <yh-dialog
            :title="`确定${enumS[statusType]}以下监控规则吗？（已自动过滤“状态”为“${enumS[statusType]}”的监控规则）`"
            :visible.sync="statusVisible"
            width="600px"
            drag
        >
            <div>监控规则编码： {{ checkRowKeys.map(item => item).join(',') }}</div>
            <el-divider></el-divider>
            <div>“状态”为“启用”的监控规则： {{ checkFilterRowKeys.map(item => item).join(',') }}</div>

            <div slot="footer" class="dialog-footer">
                <el-button @click="statusVisible = false" size="mini">取 消</el-button>
                <el-button @click="handleStatus" :loading="statusLoading" size="mini" type="primary">确 定 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { Component, Prop, Vue } from 'vue-property-decorator';
import { ColumnVO, PageVO, TableConfigVO, VueObject } from '@/common/vo';
import { downLoadFile } from '@/utils/request';
import RiskPagination from '@/common/components/risk-pagination.vue';
import { dateFormat, numberFormat, timeFormat } from '@/utils/tools';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import API from '../api/monitor-rule-setting';
import { MonitorRuleDTO, MonitorRuleVO, MonitorRuleRepVO } from '../vo/monitor-rule-setting';
import RiskTableLayout from '@/common/components/risk-table-layout-plus.vue';
import DictionConstUtil from '@/utils/diction-const-util';

@Component({ name: 'MonitorRuleList', components: { RiskTableP, RiskEntryInput, RiskTableLayout, RiskPagination, RiskIconButton } })
export default class MonitorRuleList extends Vue {
    searchParams: MonitorRuleDTO = {
        codeOrName: '',
        // id: '',
        idMH: '',
        ruleName: '',
        remark: '',
        dtCtUser: '',
        dtMdUser: '',
    };
    paging: PageVO = { currentPage: 1, pageSize: 25, total: 0 };
    tableLoading: boolean = false;
    tableConfig: TableConfigVO = {
        rowKey: 'id', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableData: MonitorRuleVO[] = [];
    columns: ColumnVO[] = [
        {
            type: 'checkbox',
            selectedAll: false,
            // fixed: 'left',
            align: 'center',
            width: 60,
        },
        {
            title: '监控规则编码',
            field: 'id',
            sortable: true,
            sortField: 'N_ID',
            filters: [{ data: '' }],
            filterField: 'idMH',
            filterType: 'search',
            minWidth: 130,
        },
        {
            title: '监控规则名称',
            field: 'ruleName',
            sortable: true,
            sortField: 'C_RULE_NAME',
            filters: [{ data: '' }],
            filterType: 'search',
            minWidth: 150,
        },
        {
            title: '启用状态',
            field: 'status',
            sortable: true,
            sortField: 'C_STATUS',
            filters: [
                { label: '禁用', value: '0' },
                { label: '启用', value: '1' },
            ],
            filterField: 'statusList',
            align: 'center',
            minWidth: 100,
            render: (value, record) => DictionConstUtil.EntryStatus[value],
            style: (value, record) => {
                if (value === '1') {
                    return { color: 'green' };
                }
                return { color: 'red' };
            },
        },
        {
            title: '定时调度表达式',
            field: 'expression',
            minWidth: 120,
            // render: (value, record) => (value ? JSON.parse(value).expression : '123s'),
        },
        {
            title: '备注',
            field: 'remark',
            sortable: true,
            sortField: 'C_REMARK',
            filters: [{ data: '' }],
            filterType: 'search',
            minWidth: 180,
        },
        {
            title: '创建人',
            field: 'dtCtUserName',
            sortable: true,
            sortField: 'D_DT_CT_USER',
            filters: [{ data: '' }],
            filterField: 'dtCtUser',
            filterType: 'search',
            minWidth: 120,
        },
        {
            title: '创建时间',
            field: 'dtCtDate',
            align: 'center',
            sortable: true,
            sortField: 'D_DT_CT_DATE',
            minWidth: 120,
            render: (value, record) => dateFormat(value) + ' ' + timeFormat(record.dtCtTime),
        },
        {
            title: '更新人',
            field: 'dtMdUserName',
            sortable: true,
            sortField: 'D_DT_MD_USER',
            filters: [{ data: '' }],
            filterField: 'dtMdUser',
            filterType: 'search',
            minWidth: 120,
        },
        {
            title: '更新时间',
            field: 'dtMdDate',
            align: 'center',
            sortable: true,
            sortField: 'D_DT_MD_DATE',
            minWidth: 120,
            render: (value, record) => dateFormat(value) + ' ' + timeFormat(record.dtMdTime),
        },
        { title: '操作', field: 'operation', minWidth: 200, align: 'center' },
    ];

    checkRowKeys: string[] = [];

    deleteVisible: boolean = false;
    delLoading: boolean = false;

    detailMsg: any = {};

    statusType: string = ''; // enable || unable
    statusVisible: boolean = false;
    enumS: any = { enable: '启用', unable: '禁用' };
    checkFilterRowKeys: string[] = [];
    statusLoading: boolean = false;

    lineHightRow: any = null; // 高亮行

    async mounted() {
        this.getTableData();
    }

    /**
     * 表格数据
     */
    getTableData(): void {
        this.tableLoading = true;
        API.getMonitorRuleList({ ...this.searchParams, paging: this.paging })
            .then((res: MonitorRuleRepVO) => {
                // res.list = [
                //     {
                //         dtCtDate: 20231024,
                //         dtCtTime: 102155,
                //         dtCtUser: '705',
                //         dtCtUserName: 'zhangcheng',
                //         dtMdDate: 20231113,
                //         dtMdTime: 140603,
                //         dtMdUser: '705',
                //         dtMdUserName: 'zhangcheng',
                //         id: 101,
                //         ruleName: '采集器 JSsssONDATA11111',
                //         status: '1',
                //         taskJson: '[{"expression":"0 * * * * ?","scheduleType":"cron"}]',
                //     },
                // ];
                res.list.forEach(j => {
                    if (j.taskJson) {
                        j.expression = JSON.parse(j.taskJson)[0].expression;
                    }
                });
                this.tableData = res?.list || [];

                this.paging.total = res?.total || 0;
                this.tableLoading = false;
            })
            .finally(() => {
                this.tableLoading = false;
            });
    }

    /**
     * 按钮点击事件
     */
    handleBtn(type: string, row): void {
        if (type == 'search') {
            this.paging.currentPage = 1;
            this.getTableData();
        } else if (type == 'refresh') {
            this.getTableData();
        } else if (type == 'export') {
            // const checkedKeys = (this.$refs['risk-table'] as any).checkRowKeys;
            // const url = this.type === 'today' ? '/event/report/export' : '/event/history/report/export';
            // downLoadFile({
            //     url,
            //     method: 'post',
            //     data: checkedKeys.length ? { resultIds: checkedKeys } : this.searchParams,
            // });
            // this.$nextTick(() => {
            //     (this.$refs['risk-table'] as any).resetCheckRowKeys();
            // });
        } else if (type === 'deletes') {
            this.checkRowKeys = (this.$refs['risk-table'] as any).checkRowKeys;
            if (this.checkRowKeys.length < 1) {
                this.yh_message_warn('请先勾选监控规则!');
                return;
            }
            this.deleteVisible = true;
        } else if (type === 'look') {
            this.detailMsg = row;
            const tab = { name: 'look', title: `查看监控规则-${row.id}`, detail: this.detailMsg };
            this.$emit('addTab', tab);
        } else if (type === 'edit') {
            this.detailMsg = row;
            const tab = { name: 'edit', title: `编辑监控规则-${row.id}`, detail: this.detailMsg };
            this.$emit('addTab', tab);
        } else if (type === 'copy') {
            this.detailMsg = row;
            const tab = { name: 'copy', title: `复制监控规则-${row.id}`, detail: this.detailMsg };
            this.$emit('addTab', tab);
        } else if (type === 'delete') {
            this.checkRowKeys = [row.id];
            this.deleteVisible = true;
        } else if (type === 'add') {
            this.detailMsg = {};
            const tab = { name: 'add', title: '新增监控规则', detail: this.detailMsg };
            this.$emit('addTab', tab);
            // this.visible = true;
        } else if (type === 'enable' || type === 'unable') {
            this.checkRowKeys = (this.$refs['risk-table'] as any).checkRowKeys;
            if (this.checkRowKeys.length < 1) {
                this.yh_message_warn('请先勾选监控规则!');
                return;
            }

            const checkedRows = (this.$refs['risk-table'] as any).checkedRows; // 产品台账发版就生效
            if (type === 'enable') {
                this.checkRowKeys = checkedRows.filter(i => i.status === '0').map(e => e.id);
                this.checkFilterRowKeys = checkedRows.filter(i => i.status === '1').map(e => e.id);
            }
            if (type === 'unable') {
                this.checkRowKeys = checkedRows.filter(i => i.status === '1').map(e => e.id);
                this.checkFilterRowKeys = checkedRows.filter(i => i.status === '0').map(e => e.id);
            }

            this.statusType = type;
            this.statusVisible = true;
        } else if (type === 'run') {
            this.checkRowKeys = (this.$refs['risk-table'] as any).checkRowKeys;
            if (this.checkRowKeys.length < 1) {
                this.yh_message_warn('请先勾选监控规则!');
                return;
            }

            const keys = this.checkRowKeys.join('&ruleIds=');
            this.$axios({
                method: 'get',
                url: '/audit/dataMonitorRule/runRule?ruleIds=' + keys,
                // data: { ruleIds: this.checkRowKeys },
            }).then((res: any) => {
                this.yh_message_success('运行成功!');
            });
        }
    }

    /**
     * 切换选中行 事件
     */
    handleCurrentRow({ row }): void {
        console.log('切换选中行:', row);
        // 因为按钮事件会穿透 换一个字段存 不用currentRow
        this.lineHightRow = row;
    }

    /**
     * 删除事件
     */
    handleDelete(): void {
        this.delLoading = true;
        API.deleteMonitorRule(this.checkRowKeys)
            .then((res: any) => {
                this.yh_message_success('删除成功!');
            })
            .finally(() => {
                this.delLoading = false;
                this.deleteVisible = false;
                this.getTableData();

                this.checkRowKeys = [];
                this.$nextTick(() => {
                    (this.$refs['risk-table'] as any).resetCheckRowKeys();
                });
            });
    }

    handleStatus(): void {
        if (this.checkRowKeys.length === 0) {
            this.yh_message_error('暂无可修改的数据, 请重新选择!');
            this.statusVisible = false;
            return;
        }
        this.statusLoading = true;
        API.updateStatus(this.checkRowKeys, this.statusType === 'enable' ? '1' : '0')
            .then((res: any) => {
                this.yh_message_success('修改成功!');
            })
            .finally(() => {
                this.statusLoading = false;
                this.statusVisible = false;
                this.getTableData();

                this.checkRowKeys = [];
                this.checkFilterRowKeys = [];
                this.$nextTick(() => {
                    (this.$refs['risk-table'] as any).resetCheckRowKeys();
                });
            });
    }
}
</script>
<style lang="scss" scoped>
#monitor-rule-list {
    height: 100%;
    padding: 0 5px;
    overflow: hidden;

    .search-bar {
        border: 1px solid #d7d7d7;
        margin: 10px 0;
        padding: 0 5px;
        height: 50px;
        line-height: 50px;
    }
}

/***  collapse-tags样式 ***/
/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light {
    display: flex;
    align-items: center;
    width: 100%;
    max-width: fit-content;
    padding: 0px 5px 0 0;
    margin: 4px 0px 2px 2px;
    .el-select__tags-text {
        display: inline-block;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}
/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light:first-of-type {
    width: 63%;
}
/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light:last-of-type {
    width: 100%;
}
/***  collapse-tags样式 ***/
</style>
